//
//  XLUtilities.m
//  XLBaseModule
//
//  Created by 于鹏 on 2017/9/12.
//  Copyright © 2017年 YIVIEW. All rights reserved.
//

#import "XLUtilities.h"
#import "XLDefaultPortraitView.h"
@implementation XLUtilities

+ (NSString *)defaultUserPortrait:(RCUserInfo *)userInfo {
    NSString *filePath = [[self class]
                          getIconCachePath:[NSString
                                            stringWithFormat:@"user%@.png", userInfo.userId]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSURL *portraitPath = [NSURL fileURLWithPath:filePath];
        return [portraitPath absoluteString];
    } else {
        XLDefaultPortraitView *defaultPortrait =
        [[XLDefaultPortraitView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];
        [defaultPortrait setColorAndLabel:userInfo.userId Nickname:userInfo.name];
        UIImage *portrait = [defaultPortrait imageFromView];
        
        BOOL result = [UIImagePNGRepresentation(portrait) writeToFile:filePath
                                                           atomically:YES];
        if (result) {
            NSURL *portraitPath = [NSURL fileURLWithPath:filePath];
            return [portraitPath absoluteString];
        } else {
            return nil;
        }
    }
}

+ (NSString *)getIconCachePath:(NSString *)fileName {
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(
                                                              NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath =
    [cachPath stringByAppendingPathComponent:
     [NSString stringWithFormat:@"CachedIcons/%@",
      fileName]]; // 保存文件的名称
    
    NSString *dirPath = [cachPath
                         stringByAppendingPathComponent:[NSString
                                                         stringWithFormat:@"CachedIcons"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:dirPath]) {
        [fileManager createDirectoryAtPath:dirPath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
    return filePath;
}

@end
